<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2021/5/24
 * Time: 11:47
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

declare(strict_types=1);

namespace app\common\lib\sms;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use think\Exception;
use think\facade\Log;

class AliSms implements BaseSms
{
    /**
     * @param string $phone
     * @param int $code
     * @return bool
     * @throws Exception
     */
    public static function sendSms(string $phone = '', int $code = 0): bool
    {
        if (empty($phone) || empty($code)) {
            throw new Exception("参数不能为空");
        }
        $data = [
            "code" => $code
        ];
        $aliConf = config('aliyun');
        $client = self::createClient($aliConf["accessKeyId"], $aliConf["accessKeySecret"]);
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $phone,
            "signName" => $aliConf['signName'],
            "templateCode" => $aliConf['templateCode'],
            "templateParam" => json_encode($data)
        ]);
        $result = $client->sendSms($sendSmsRequest);
        $ret = $result->body;
        if ($ret->code == "OK") {
            return true;
        } else {
            return false;
        }
    }

    public static function createClient($accessKeyId, $accessKeySecret)
    {
        $config = new Config([
            // 您的AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 您的AccessKey Secret
            "accessKeySecret" => $accessKeySecret
        ]);
        // 访问的域名
        $config->endpoint = "dysmsapi.aliyuncs.com";

        return new Dysmsapi($config);
    }
}